<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\Request;
use think\facade\View;
use app\validate\CheckRole;
use think\exception\ValidateException;


// 角色管理
class Role extends BaseController
{
    public function index()
    {
        return View::fetch();
    }


    public function load(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $data = Db::name('admin_role')
            ->field('id, rolename, type, add_time')
            ->order('id desc')
            ->select();

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => 0,
            'data'=> $data
        );
        return json($data);
    }


    public function add()
    {
        return View::fetch();
    }

    public function getTree(Request $request)
    {
        $role_id = $request->get('role_id');
        $where['status'] = 1;
        $result = Db::name('admin_menu')
            ->field('id, title, menu_id as pid, powerType')
            ->where($where)
            ->order('sort asc,id asc')
            ->select()->toArray();
        $rule = Db::name('admin_role')->where(['id'=>$role_id])->find();
        if ($role_id) {
            foreach ($result as &$v) {
                if ($v['powerType'] == 2) {
                    if (in_array($v['id'], explode(',', $rule['rule']))) {
                        $v['checked'] = true;
                    } else {
                        $v['checked'] = false;
                    }
                }

                $v['spread'] = true;
            }
        }

        $menu = getTree($result);

        header('Content-Type:application/json; charset=utf-8');
        return json($menu);
    }

    public function save(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();

        // 验证
        try {

            validate(CheckRole::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }

        Db::startTrans();
        try {
            $insert = array(
                'rolename' => $post['rolename'],
                'rule' => $post['rule'],
                'type' => $post['type'],
                'add_time' => time(),
                'update_time' => time()
            );
            $getId = Db::table('o_admin_role')->insertGetId($insert);
            if (!$getId) {
                Db::rollback();
                return $this->outputAjax('提交失败！');
            }

            Db::commit();
            return $this->outputAjax('提交成功！',0);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }


    public function edit(Request $request)
    {
        $id = $request->get('id');

        $inf = Db::name('admin_role')
            ->where(array('id' => $id))
            ->field('id, rolename, rule, type')
            ->find();
        View::assign('inf', $inf);
        return View::fetch();
    }


    public function modify(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $this->request->post();

        // 验证
        try {

            validate(CheckRole::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }

        Db::startTrans();
        try {
            $update = array(
                'id' => $post['id'],
                'rolename' => $post['rolename'],
                'type' => $post['type'],
                'rule' => $post['rule'],
                'update_time' => time()
            );

            if (!Db::table('o_admin_role')->update($update)) {
                Db::rollback();
                return $this->outputAjax('提交失败！');
            }

            Db::commit();
            return $this->outputAjax('提交成功！',0);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }

    public function delete(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');
        if(!$id){
            return $this->outputAjax('参数不足！');
        }

        try {
            $res = Db::name('admin_user')->where('role_id', $id)->find();

            if ($res) {
                return $this->outputAjax('删除失败, 该角色已绑定登录账户');
            }

            $result = Db::name('admin_role')->where('id','=',$id)->delete();

            if(!$result){
                return $this->outputAjax('删除失败！');
            }
            return $this->outputAjax('删除成功！',0);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }
}